package com.example.myapplication;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.LauncherActivity;
import android.app.ListActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Telephony;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;




import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;



public class RateActivity extends ListActivity implements Runnable{
    Handler handler=new Handler();
    private static final String TAG = "RateActivity";

    public void setHandler(Handler handler) {
        this.handler = handler;
    }
    private String logDate = "";
    private final String DATE_SP_KEY = "lastRateDateStr";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.rateactivity);
        SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
        logDate = sp.getString(DATE_SP_KEY, "");
        Log.i("List","lastRateDateStr=" + logDate);






        //List<String> rateList = new ArrayList<String>();
        handler=new Handler(Looper.myLooper()){
            public void handleMessage(@NonNull Message msg){
                if(msg.what==11){
                    Log.i(TAG,"handleMessage:内容："+msg.obj);
                    Toast.makeText(RateActivity.this,"收到"+msg.obj,Toast.LENGTH_SHORT).show();
                    List<String> rateList=(List<String>)msg.obj;
                    ListAdapter adapter = new ArrayAdapter<String>(RateActivity.this,android.R.layout.simple_list_item_1,rateList);
                    setListAdapter(adapter);


                }
                super.handleMessage(msg);
            }


        };
        Thread t = new Thread((Runnable) this);
        t.start();
        Log.i(TAG,"OnCreate:t.start()....");
    }




    public void run() {
        Log.i(TAG,"run:()....");
        List<String> retList = new ArrayList<String>();
        String curDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
        if(curDateStr.equals(logDate)){
            //如果相等，则不从网络中获取数据
            Log.i("run","日期相等，从数据库中获取数据");
            RateManager dbManager = new RateManager(RateActivity.this);
            for(RateItem rateItem : dbManager.listAll()){
                retList.add(rateItem.getCname() + "=>" + rateItem.getCval());
            }}else{
                Log.i("run","日期相等，从网络中获取在线数据");


            try {
                List<RateItem> rateList = new ArrayList<RateItem>();

            SSLAgent.getInstance().trustAllHttpsCertificates();
            Document doc = Jsoup.connect("https://www.huilvzaixian.com/").get();
            Elements tables = doc.getElementsByTag("ul");
            Element table = tables.get(3);
            Element li = table.getElementsByTag("li").get(0);
            Elements a = li.getElementsByTag("a");
            for (Element tr : a) {
                //Log.i(TAG,"run:tr="+tr);
                String[] words = tr.text().split(" ");
                String rname=words[1];
                String rate_str=words[2];
                Log.i(TAG,"run:币种:"+rname+"==>"+rate_str);

                //HashMap<String,String> map=new HashMap<String,String>();
                //map.put("Title",rname);
                //map.put("detail",rate_str);
                //rateList.add(rname);
                //rateList.add(rate_str);
                RateItem rateItem = new RateItem(rname,Float.parseFloat(rate_str));
                rateList.add(rateItem);


            }
                RateManager dbManager = new RateManager(RateActivity.this);
                dbManager.deleteAll();
                Log.i("db","删除所有记录");
                dbManager.addAll(rateList);
                Log.i("db","添加新记录集");}catch(MalformedURLException e){
                Log.e("www", e.toString());
                e.printStackTrace();
            }catch(IOException e){
                Log.e("www", e.toString());
                e.printStackTrace();
            }
            SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sp.edit();
            edit.putString(DATE_SP_KEY, curDateStr);
            edit.commit();


            Log.i("run","更新日期结束：" + curDateStr);
            Message msg = handler.obtainMessage(11);
            msg.obj = retList;
            handler.sendMessage(msg);
            Log.i(TAG, "run:msg已发送");
        }



    }}